package database

import (
	"database/sql"
	"fmt"
	"gitee.com/z930255076/go-ext/log"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"os"
	"strconv"
	"time"
)

var (
	Sql *sql.DB
	DB  *gorm.DB
)

func init() {
	UserName := os.Getenv("DB_USERNAME")
	Password := os.Getenv("DB_PASSWORD")
	Addr := os.Getenv("DB_HOST")
	Port, _ := strconv.Atoi(os.Getenv("DB_PORT"))
	Database := os.Getenv("DB_DATABASE")
	Prefix := os.Getenv("DB_PREFIX")
	logLevel := os.Getenv("LOG_LEVEL")
	MaxLifetime := 10
	MaxOpenConns := 10
	MaxIdleConns := 10

	// 开启日志
	fileLogger := log.NewSqlLogger(logLevel)

	// 组装连接字符串
	conn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", UserName, Password, Addr, Port, Database)

	db, err := gorm.Open(mysql.New(mysql.Config{
		DSN: conn,
	}), &gorm.Config{
		//Logger: logger.Default.LogMode(logger.Silent),
		Logger: fileLogger,
		NamingStrategy: schema.NamingStrategy{
			TablePrefix: Prefix,
		},
	})

	if err != nil {
		panic("mysql连接错误:" + err.Error())
	}

	sqlDB, err := db.DB()
	if err := sqlDB.Ping(); err != nil {
		panic("mysql ping 失败:" + err.Error())
	}

	// 指定连接数
	sqlDB.SetConnMaxLifetime(time.Duration(MaxLifetime) * time.Second)
	sqlDB.SetMaxOpenConns(MaxOpenConns)
	sqlDB.SetMaxIdleConns(MaxIdleConns)

	Sql = sqlDB
	DB = db
}
